import tkinter as tk
from tkinter import ttk
from typing import List, Tuple
from .folder_selector import FolderSelector
from tkinter import filedialog
from .configs import AppConfig
from .layouts import Vertical


class PathsList(ttk.Frame):
    def __init__(self, master=None):
        super().__init__(master)
        self.pack()
        self.create_widgets()

    def create_widgets(self):
        self.listbox = tk.Listbox(self)
        self.listbox.pack(side="left", fill="both", expand=True)
        self.listbox.bind("<<ListboxSelect>>", self.on_select)

        # def add_buttons()
        self.right_bar = Vertical(self)

        self.add_button = ttk.Button(self.right_bar, text="添加", command=self.add_item)
        # self.add_button.pack()

        self.delete_button = ttk.Button(
            self.right_bar, text="删除", command=self.delete_item
        )
        # self.delete_button.pack()
        self.right_bar.add(self.add_button)
        self.right_bar.add(self.delete_button)
        self.right_bar.pack(side="left", fill="y", padx=6)

        config = AppConfig()
        for path in config.paths:
            self.listbox.insert(tk.END, path)

    def update_config(self):
        paths = self.values()
        cfg = AppConfig()
        cfg.paths = paths
        cfg.sync_to_disk()

    def add_item(self):
        folder_path = filedialog.askdirectory(initialdir=self.get_selection())
        if folder_path:
            self.listbox.insert(tk.END, folder_path)
            self.update_config()

    def delete_item(self):
        selected_index = self.listbox.curselection()
        if selected_index:
            self.listbox.delete(selected_index)
            self.update_config()

    def values(self) -> List[str]:
        items = self.listbox.get(0, tk.END)
        return list(items)

    def on_select(self, evt):
        pass

    def get_selection(self) -> str:
        selected_index = self.listbox.curselection()
        if selected_index:
            return self.listbox.get(selected_index)
        return ""
